<template>
	<el-dialog :title="title" v-model="open" append-to-body :close-on-click-modal="false" width="90%">
		<!-- <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
			<el-row :gutter="10" class="mb20">
				<el-col :span="12">
					<el-form-item label="名称" prop="name">
						<el-input v-model="form.name" placeholder="请输入名称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="thumb">
						<template #label>
							相册封面图<br />
							宽高比例13:8<br />
							建议(260*160)<br />
							大小不超过2M
						</template>
						<image-upload-cOS v-model="form.thumb" ref="imageUploadThumbRef" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="10" class="mb20">
				<el-col>
					<el-form-item label="名称" prop="details">
						<editor :is-disable="false" v-model="form.details" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form> -->
		<el-row :gutter="10">
			<el-col :span="21">
				<span style="color: red"> 注：目前第一个规格可以设置不同的规格图片。设置后，用户选择不同规格会显示不同图片（建议尺寸：160 x 160像素） </span>
			</el-col>
			<el-col :span="3">
				<el-button @click="onAddSpecs" plain icon="el-icon-plus"> 新增规格项目 </el-button>
			</el-col>
		</el-row>
		<el-table :data="specifications" border class="theme-2">
			<el-table-column label="规格名" width="130" align="center">
				<template #default="scope">
					<el-input v-model="scope.row.name" placeholder="请输入规格名" />
				</template>
			</el-table-column>
			<el-table-column label="规格值" align="center">
				<template #default="scope">
					<template v-if="scope.$index">
						<el-tag
							v-for="(item2, index2) in scope.row.leaf"
							:key="index2"
							closable
							size="medium"
							@close="onDeleteAttributeItem(scope.$index, index2)"
						>
							{{ item2.name }}
						</el-tag>
					</template>
					<template v-else>
						<div v-for="(item2, index2) in scope.row.leaf" :key="index2" class="img_sku-item">
							<el-tag closable size="medium" @close="onDeleteAttributeItem(scope.$index, index2)">{{ item2.name }}</el-tag>
							<div class="img_sku-item__upload">
								<div class="arrow" />
								<div class="upload-img">
									<el-upload
										:action="uploadImgUrl"
										:headers="headers"
										:show-file-list="false"
										accept="image/jpeg,image/jpg,image/png"
										:on-success="(response:any) => onUploadSuccess(response, scope.$index, index2)"
										:on-error="onUploadError"
										:before-upload="beforeImagesUpload"
										class="img-uploader"
									>
										<el-image v-if="item2.icon" :src="item2.icon" fit="scale-down" />
										<i v-else class="el-icon-upload uploader-icon"></i>
									</el-upload>
								</div>
							</div>
						</div>
					</template>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" width="300">
				<template #default="scope">
					<el-row :gutter="10">
						<el-col :span="18">
							<el-input v-model="scope.row.addAttribute" @keyup.enter="onAddAttribute(scope.$index)" placeholder="新增一个规格属性">
								<template #append>
									<el-button icon="el-icon-plus" @click="onAddAttribute(scope.$index)">添加</el-button>
								</template>
							</el-input>
						</el-col>
						<el-col :span="6">
							<el-button v-if="Number(scope.$index)" type="danger" @click="onDeleteAttribute(scope.$index)">删除</el-button>
						</el-col>
					</el-row>
				</template>
			</el-table-column>
		</el-table>
		<el-table :data="specifications_val" border>
			<el-table-column label="规格属性" align="center">
				<template #default="scope">
					{{ scope.row.skus.map((item: any) => item.v).join('_') }}
				</template>
			</el-table-column>
			<el-table-column label="图片" align="center">
				<template #default="scope">
					<el-image v-if="scope.row.icon" :src="scope.row.icon" fit="scale-down" style="width: 50px; height: 50px" />
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<span class="required_title"> 库存 </span>
					<el-button type="info" @click="onBatchSet('stock')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.stock" :min="0" :precision="0" :controls="false" placeholder="请输入库存" />
				</template>
			</el-table-column>
			<el-table-column label="原价" align="center">
				<template #header>
					<span class="required_title"> 原价 </span>
					<el-button type="info" @click="onBatchSet('old_price')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.old_price" :min="0" :precision="0" :controls="false" placeholder="请输入原价" />
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<span class="required_title"> 成本价 </span>
					<el-button type="info" @click="onBatchSet('cost_price')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.cost_price" :min="0" :precision="0" :controls="false" placeholder="请输入成本价" />
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<span class="required_title"> 管家佣金 </span>
					<el-button type="info" @click="onBatchSet('agent_price1')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.agent_price1" :min="0" :precision="0" :controls="false" placeholder="请输入管家佣金" />
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<span class="required_title"> 公司佣金 </span>
					<el-button type="info" @click="onBatchSet('agent_price2')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.agent_price2" :min="0" :precision="0" :controls="false" placeholder="请输入公司佣金" />
				</template>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<span class="required_title"> 平台服务费 </span>
					<el-button type="info" @click="onBatchSet('service_price')">同步</el-button>
				</template>
				<template #default="scope">
					<el-input-number v-model="scope.row.service_price" :min="0" :precision="0" :controls="false" placeholder="请输入平台服务费" />
				</template>
			</el-table-column>
			<el-table-column align="center" prop="service_price">
				<template #header>
					售价
					<el-tooltip effect="dark" content="售价 = 成本价 + 管家佣金 + 公司佣金 + 平台服务费" placement="top">
						<i class="el-icon-info" />
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" :loading="submitLoading" @click="onSubmitForm">确定</el-button>
				<el-button @click="onCancel">取消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts">
import { nextTick, reactive, ref, toRefs } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';

// import Editor from '/@/components/editor/index.vue';

export default {
	name: 'generalDialog',
	// components: { Editor },
	setup() {
		const state = reactive({
			title: 'generalDialog',
			open: false,
			form: {} as any,
			rules: {
				name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
			}, // 表单校验
			submitLoading: false,
			uploadImgUrl: `${import.meta.env.VITE_API_URL}/admin/upload_gooods_specs_icon`,
			headers: {
				token: Session.get('token'),
			},
			specifications: [
				{
					id: '1',
					addAttribute: '',
					name: '',
					leaf: [] as any,
				},
			],
			specifications_val: [] as any,
		});

		const formRef = ref(null);
		const imageUploadThumbRef = ref(null);
		const loadingUploadRef = ref();
		let callback: Function = () => {};

		/********** 点击事件(on开头) **********/
		// 新增SKU
		const onAddSpecs = () => {
			// if (!state.specifications.length) {
			// 	state.specifications.push({
			// 		id: '1',
			// 		addAttribute: '',
			// 		name: '',
			// 		leaf: [],
			// 	});
			// 	return true;
			// }
			if (!state.specifications[state.specifications.length - 1].name || !state.specifications[state.specifications.length - 1].leaf.length) {
				ElMessage.warning('请完善已有规格');
				return true;
			}
			state.specifications.push({
				id: String(Number(state.specifications[state.specifications.length - 1].id) + 1),
				addAttribute: '',
				name: '',
				leaf: [],
			});
		};
		// 新增SKU属性
		const onAddAttribute = (index: number) => {
			if (!state.specifications[index].name) {
				ElMessage.warning('请输入规格名');
				return true;
			}
			state.specifications[index].addAttribute = state.specifications[index].addAttribute.trim();
			if (state.specifications[index].addAttribute) {
				if (!state.specifications[index].addAttribute.includes('_')) {
					if (state.specifications[index].leaf.length) {
						state.specifications[index].leaf.push({
							id: String(Number(state.specifications[index].leaf[state.specifications[index].leaf.length - 1].id) + 1),
							name: state.specifications[index].addAttribute,
							icon: '',
						});
					} else {
						state.specifications[index].leaf.push({
							id: state.specifications[index].id + '1',
							name: state.specifications[index].addAttribute,
							icon: '',
						});
					}
				} else {
					ElMessage.warning('规格里不允许出现「 _ 」字符，请检查后重新添加');
				}
			}
			combinationAttribute();
		};
		// 上传图片
		const onUploadSuccess = (res: any, index: number, index2: number) => {
			state.specifications[index].leaf[index2].icon = res.data.info.show_url;
			state.specifications_val = state.specifications_val.map((item: any) => {
				return {
					...item,
					icon: state.specifications[index].leaf[index2].id == item.skus[0].v_id ? res.data.info.show_url : item.icon,
				};
			});
			(loadingUploadRef.value as any)?.close();
		};
		const onUploadError = () => {
			ElMessage.error('上传失败');
			(loadingUploadRef.value as any)?.close();
		};
		// 上传图片校验
		const beforeImagesUpload = (file: any) => {
			let types = ['image/jpeg', 'image/png', 'image/jpg'];
			const isJPG = types.includes(file.type);
			const isLt2M = file.size / 1024 / 1024 < 1;
			if (!isJPG) {
				ElMessage.warning('只能是 jpeg,png,jpg 格式');
				return isJPG;
			}
			if (!isLt2M) {
				ElMessage.warning('上传图片大小不能超过 1M');
				return isLt2M;
			}
			(loadingUploadRef.value as any) = ElLoading.service({
				lock: true,
				text: '上传中',
				background: 'rgba(0, 0, 0, 0.7)',
			});
		};
		// 删除SKU
		const onDeleteAttribute = (index: number) => {
			state.specifications.splice(index, 1);
			combinationAttribute();
		};
		// 删除SKU某项属性
		const onDeleteAttributeItem = (index1: number, index2: number) => {
			state.specifications[index1].leaf.splice(index2, 1);
			combinationAttribute();
		};
		//批量设置
		const onBatchSet = (type: string) => {
			state.specifications_val = state.specifications_val.map((item: any) => {
				return {
					...item,
					stock: type == 'stock' ? state.specifications_val[0].stock : item.stock,
					old_price: type == 'old_price' ? state.specifications_val[0].old_price : item.old_price,
					cost_price: type == 'cost_price' ? state.specifications_val[0].cost_price : item.cost_price,
					agent_price1: type == 'agent_price1' ? state.specifications_val[0].agent_price1 : item.agent_price1,
					agent_price2: type == 'agent_price2' ? state.specifications_val[0].agent_price2 : item.agent_price2,
					service_price: type == 'service_price' ? state.specifications_val[0].service_price : item.service_price,
				};
			});
		};
		/** 提交按钮 */
		const onSubmitForm = () => {
			(formRef.value as any)?.validate((valid: boolean) => {
				if (valid) {
					state.submitLoading = true;
					console.log('state.form', state.form);

					onCancel();
					callback();
				}
			});
		};
		// 取消按钮
		const onCancel = () => {
			state.submitLoading = false;
			state.open = false;
			reset();
			nextTick(() => {
				(imageUploadThumbRef.value as any)?.dataLoading();
			});
		};

		/********** 方法事件 **********/
		//打开
		const openDialog = (config: any, fn: Function) => {
			console.log(config);
			callback = fn;
			state.open = true;
			reset();
			// let specifications = state.specifications.map((item: any) => {
			// 	return item.leaf.map((item1: any) => item1.name);
			// });
			// let specifications_val = calcDescartes(specifications).map((item: any) => {
			// 	let skus: any = [];
			// 	let icon = '';
			// 	state.specifications.map((item1: any, index: number) => {
			// 		item1.leaf.map((item2: any) => {
			// 			if (item2.name === item[index]) {
			// 				skus.push({
			// 					k: item1.name,
			// 					k_id: item1.id,
			// 					v: item2.name,
			// 					v_id: item2.id,
			// 				});
			// 			}
			// 		});
			// 	});
			// 	state.specifications[0].leaf.map((item1: any) => {
			// 		if (item1.name == item[0]) {
			// 			icon = '';
			// 		}
			// 	});
			// 	return {
			// 		stock: 0,
			// 		old_price: 0,
			// 		cost_price: 0,
			// 		agent_price1: 0,
			// 		agent_price2: 0,
			// 		service_price: 0,
			// 		skus: skus,
			// 		icon,
			// 	};
			// });
			// state.specifications_val = specifications_val;
		};
		// 表单重置
		const reset = () => {
			state.form = {
				name: '',
				thumb: '',
				details: '',
			};
			(formRef.value as any)?.resetFields();
			nextTick(() => {
				(imageUploadThumbRef.value as any)?.reset();
			});
		};
		// 生成sku
		const calcDescartes = (array: any) => {
			if (array.length < 2) return array[0].map((item: any) => [item]) || [];
			return Array.prototype.reduce.call(
				array,
				(col: any, set: any) => {
					var res: any = [];
					col.forEach((c: any) => {
						set.forEach((s: any) => {
							res.push(c.concat([s]));
						});
					});
					return res;
				},
				[[]]
			);
		};
		// 生成 skuData 数据
		const combinationAttribute = () => {
			let specifications = state.specifications.map((item: any) => {
				return item.leaf.map((item1: any) => item1.name);
			});
			let specifications_val = calcDescartes(specifications).map((item: any) => {
				let skus: any = [];
				let icon = '';
				state.specifications.map((item1: any, index: number) => {
					item1.leaf.map((item2: any) => {
						if (item2.name === item[index]) {
							skus.push({
								k: item1.name,
								k_id: item1.id,
								v: item2.name,
								v_id: item2.id,
							});
						}
					});
				});
				state.specifications[0].leaf.map((item1: any) => {
					if (item1.name == item[0]) {
						icon = item1.icon;
					}
				});
				return {
					stock: 0,
					old_price: 0,
					cost_price: 0,
					agent_price1: 0,
					agent_price2: 0,
					service_price: 0,
					skus: skus,
					icon,
				};
			});
			state.specifications_val = specifications_val;
		};

		return {
			formRef,
			imageUploadThumbRef,
			onAddSpecs,
			onAddAttribute,
			onUploadSuccess,
			onUploadError,
			beforeImagesUpload,
			onDeleteAttribute,
			onDeleteAttributeItem,
			onBatchSet,
			onSubmitForm,
			openDialog,
			onCancel,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped>
.theme-2 {
	border: 1px solid #ebeef5;
	border-bottom: 0;
	margin-bottom: 20px;
	.el-tag {
		margin-right: 10px;
	}
	.img_sku-item {
		display: inline-block;
		margin-right: 30px;
		vertical-align: middle;
		.img_sku-item__upload {
			width: 94px;
			height: 94px;
			margin-top: 6px;
			padding: 4px;
			border: 1px solid #e5e5e5;
			border-radius: 4px;
			background-color: #fff;
			position: relative;
			margin-bottom: 10px;

			.arrow {
				position: absolute;
				width: 0;
				height: 0;
				top: -8px;
				left: 10%;
				border-style: solid;
				border-color: transparent;
				border-left: 5px solid transparent;
				border-right: 5px solid transparent;
				border-bottom: 5px solid #333;

				&::after {
					position: absolute;
					display: block;
					width: 0;
					height: 0;
					top: 0;
					margin-left: -10px;
					border-color: transparent transparent #fff;
					border-style: solid;
					border-width: 0 10px 10px;
					content: '';
				}
			}

			.el-image,
			.img-uploader,
			.uploader-icon {
				width: 84px;
				height: 84px;
			}

			.uploader-icon {
				line-height: 84px;
				font-size: 30px;
			}

			.el-image {
				display: block;
			}
		}
	}
}
.required_title::before {
	content: '*';
	color: #f56c6c;
}
</style>
